<?php

namespace app\admin\controller\eduadmin;
use think\Session;
use think\Db;
use app\common\controller\Backend;

/**
 * 班级管理
 *
 * @icon fa fa-circle-o
 */
class Classes extends Backend
{
    
    /**
     * Classes模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Classes');
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

            /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            // 绑定id字段的文字显示
            $list = addtion($list, [
                [
                    'field'    => 'branchids',
                    'display'  => 'branch_names',
                    'primary'  => 'id',
                    'column'   => 'name',
                    'model'    => '\app\admin\model\Branch',
                    'name'     => 'Branch',
                    'table'    => 'Branch'
                ],
                [
                    'field'    => 'teacher',
                    'display'  => 'teacher_name',
                    'primary'  => 'id',
                    'column'   => 'nickname',
                    'model'    => '\app\admin\model\Admin',
                    'name'     => 'Admin',
                    'table'    => 'Admin'
                ],
                [
                    'field'    => 'courseid',
                    'display'  => 'course_name',
                    'primary'  => 'id',
                    'column'   => 'name',
                    'model'    => '\app\admin\model\Course',
                    'name'     => 'Course',
                    'table'    => 'Course'
                ]
            ]);

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

     /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
              
                try
                {
                   //获取登录用户
                    $admin =Session::get("admin");                   
                    //创建人
                    $params["createby"] = $admin["username"];

                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


     /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //获取登录用户
                    $admin =Session::get("admin");                   
                    //创建人
                    $params["updateby"] = $admin["username"];

                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


         /**
     * Selectpage搜索
     * 
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }


    //添加学员
	public function addStudent()
    {
		if(input('?post.classid')&&input('?post.enrollid')){
			$classid = input('classid');
			$enrollid = input('enrollid');
			$enrollidArr = explode(',', $enrollid);
			foreach ($enrollidArr as $k => $v) {
                $count =  Db::name('Classesgroup')
                    ->where('class_id',$classid)
                    ->where('enroll_id',$v)
                    ->count();
                if($count>0){
                    return ['code'=>'FAIL','msg'=>'重复添加！'];
                }
				$inData['class_id'] = $classid;
                $inData['enroll_id'] = $v;
                Db::name('Classesgroup')->insert($inData);
                Db::name('Enroll')->where('id',$v)->update(['status'=>'已分班']);
            }
            //更新招生人数
            $studentcount = Db::name('Classesgroup')->where('class_id',$classid)->count();
            Db::name('Classes')->where('id',$classid)->update(['enrollcount'=>$studentcount]);
    		return ['code'=>'SUCCESS','msg'=>'添加成功！'];
		}else{
			return ['code'=>'FAIL','msg'=>'参数传递错误！'];
		}
	}
	//删除学员
	public function delStudent()
    {
		if(input('?post.classid')&&input('?post.enrollid')){
			$classid = input('classid');
			$enrollid = input('enrollid');
			$enrollidArr = explode(',', $enrollid);
			foreach ($enrollidArr as $k => $v) {
				Db::name('Classesgroup')
                    ->where('class_id',$classid)
                    ->where('enroll_id',$v)
                    ->delete();
                Db::name('Enroll')->where('id',$v)->update(['status'=>'未分班']);
            }
            //更新招生人数
            $studentcount = Db::name('Classesgroup')->where('class_id',$classid)->count();
            Db::name('Classes')->where('id',$classid)->update(['enrollcount'=>$studentcount]);
    		return ['code'=>'SUCCESS','msg'=>'删除成功！'];
		}else{
			return ['code'=>'FAIL','msg'=>'参数传递错误！'];
		}
	}

}
